/**
 * 长春市支点科技有限公司 [ http://www.4006660407.com ]
 * 小程序代码对外公开，以供大家进行参考和使用
 * 小程序中各项界面数据均已模拟，只需要简单的开发即可实际应用
 * 后台代码因版权原因无法公开，请谅解
 * 如需后端代码请咨询：400-666-0407
 * 或搜索微信公众号 zhidianweixin 或 支点Fulcrum
 * 共享茶室无缝对接互联网+时代，
 * 专业解决商务人士稳定而高频的商谈空间需求稀缺的痛点，
 * 符合各大企业外勤人员、小微企业创业 人员、自由职业者、异地差旅人士、小型会议、品茶爱好者等群体的需求。
 * 通过物联网技术实现无人值守的管理系统，
 * 开创全新“低门槛”、“高隐私”、“无营销”，
 * 24小时不打烊智能共享茶室模式。
 * 是您休闲会客、静心的好去处。
 * 已为多家茶馆提供专业管理系统解决方案。
 */
//获取应用实例
const app = getApp();
// 引入SDK核心类
const QQMapWX = require('../../lib/qqmap-wx-jssdk.min');
const HtmlParser = require('../../utils/html-view/index');
const key = 'QYUBZ-AGNC2-ISZUO-CVF3A-PDBUF-E7F2J'; //使用在腾讯位置服务申请的key
// 实例化API核心类
const qqmapsdk = new QQMapWX({
    key: key // 必填
});
Page({
  data: {
    id:0,
    pid:0,
    oid:0,
    dr:[],
    house:[],
    room:[],
    order:[],
    current:0,
    xuanze:[],
    changetime:'hide', //初始化隐藏
    notimes:[], //已经被预定的时间段
    mintime:2, //最小预定时间
    times:{},//时间戳区间
    tmq:'请选择时间',
    tmh:0,//购买小时数
    money:0.00,
    tmselect:['1小时','1.5小时','2小时','2.5小时','3小时','3.5小时','4小时'],
    tmoption:[{min: 1,name: '1小时'},{min: 1.5,name: '1.5小时'},{min: 2,name: '2小时'},{min: 2.5,name: '2.5小时'},{min: 3,name: '3小时'},{min: 3.5,name: '3.5小时'},{min: 4,name: '4小时'}],
    tmindex:0,
    coupon_text:"" //编译后的文本
  },
  onLoad: function (option) {
    var that = this;
    var dr = app.globalData.dr;
    that.setData({
      id:option.id,
      pid:option.pid,
      oid:option.oid?option.oid:0,
      dr:dr
    });
    //获取房间信息
    that.getRoom();
  },
  onShow:function(){
    wx.showShareMenu({
      withShareTicket:true,
      menus:['shareAppMessage','shareTimeline']
    })
  },
  //选择时间
  bindPickerChange:function(option){
    var danjia = this.data.room.money;
    var time = this.data.tmoption[option.detail.value]['min'];
    this.setData({
      tmindex: option.detail.value,
      tmh:time,
      money:time*danjia
    })
  },
  //支付
  zhifu:function(){
    wx.navigateTo({
      url: '/pages/pay/index?id=1'
    })
  },
  //获取房间
  getRoom:function(){
    let that = this;
    var res = {
        "house": {
            "id": 7,
            "name": "支点科技店",
            "address": "支点科技",
            "yytime": "00:00 ~ 24:00",
            "lng": 110.196109,
            "lat": 20.045091,
            "desc": "欢迎光临",
            "tel": "4006660407"
        },
        "room": {
            "id": 28,
            "pid": 7,
            "name": "星辰大海",
            "ymoney": "200.00",
            "money": "100",
            "num": 18,
            "renshu": "1",
            "qiding": "2",
            "content": "<p>欢迎光临</p>",
            "pic": ["/image/cs01.jpg","/image/cs02.jpg"]
        },
        "times": [],
        "order": [],
        "xuanze": {
            "sdate": "04月01日 11:00",
            "edate": "04月01日 13:00",
            "stime": 1617246000,
            "etime": 1617253200
        },
        "qd": 2
    };
    
      //解析在线编辑器内容
      var content = res.room.content;
      if(content){
          var  coupon_text = new HtmlParser(content).nodes;
          that.setData({
            coupon_text:coupon_text
          })
      }
      that.setData({
        house:res.house,
        room:res.room,
        notimes:res.times,
        order:res.order,
        mintime:res.room.qiding,
        times:{stime:res.xuanze.stime*1000,etime:res.xuanze.etime*1000},
        tmh:res.qd,
        tmq:res.xuanze.sdate+' - '+res.xuanze.edate,
        xuanze:res.xuanze,
        money:res.qd*res.room.money
      });
      that.getJuli();
  },
  //获取时间
  onchangetime:function(){
    this.setData({
      changetime:'show'
    });
  },
  clickSure:function(e){
    var d = e.detail;
    var dj = this.data.room.money;
    //计算时间
    var D = ['00','01','02','03','04','05','06','07','08','09'];
    var stime = new Date(d.stime);
    var start = (D[stime.getMonth()+1]||stime.getMonth()+1)+'月' + (D[stime.getDate()]||stime.getDate()) + ' ' + (D[stime.getHours()]||stime.getHours()) + ':' + (D[stime.getMinutes()]||stime.getMinutes());
    var etime = new Date(d.etime);
    var end = (D[etime.getMonth()+1]||etime.getMonth()+1)+'月' + (D[etime.getDate()]||etime.getDate()) + ' ' + (D[etime.getHours()]||etime.getHours()) + ':' + (D[etime.getMinutes()]||etime.getMinutes());
    this.setData({
      times:{stime:d.stime,etime:d.etime},//时间戳区间
      tmq:start+' - '+end,
      tmh:d.es,//购买小时数
      money:d.es*dj
    });
  },
  daohang:function(){
    var that = this;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success (res) {
        wx.openLocation({
          latitude:that.data.house.lat,
          longitude:that.data.house.lng,
          scale: 18,
          name: that.data.house.name,
          address: that.data.house.address
        })
      }
     })
  },
  swiperChange: function(e) {
      this.setData({
        current: e.detail.current
      })
  },
  getJuli:function(){
    var that = this;
    var thiscity = app.globalData.thiscity;
    if(JSON.stringify(thiscity) === '{}'){
      //逆地址解析
     qqmapsdk.reverseGeocoder({
        location: '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
        success: function(res) {//成功后的回调
          var lng = res.result.ad_info.location.lng;
          var lat=res.result.ad_info.location.lat;
          //获取驾车距离
          that.getMapDriving([lng,lat,that.data.house.lng,that.data.house.lat]);
        },
        fail: function(error) {
          console.error(error);
        }
      })
    }else{
      var lng = thiscity.lng;
      var lat = thiscity.lat;
      //获取驾车距离
      that.getMapDriving([lng,lat,that.data.house.lng,that.data.house.lat]);
    }
  },
  //获取地点实际路线距离和驾车时间
  getMapDriving:function(e) {
    var _this = this;
    var juli = 0;
    var time = 0;
    //调用距离计算接口
    qqmapsdk.direction({
      mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      //from参数不填默认当前地址
      from: {latitude: e[1],longitude: e[0]},
      to: {latitude: e[3],longitude: e[2]}, 
      success: function (res) {
        var ret = res.result.routes[0];
        juli = ret.distance;
        time = ret.duration;
        if (time > 60) {
          //大于一小时
          time = Math.floor(time/60 * 100) / 100;
          time = time.toFixed(2)*1 + '小时';
        } else {
          //小于一小时
          time = time.toFixed(2)*1 + '分钟';
        }
        if (juli > 1000) {
          //大于1000米时
          juli = Math.floor(juli/1000 * 100) / 100;
          juli = juli.toFixed(2)*1 + 'km';
        } else {
          //小于1000米直接返回
          juli = juli.toFixed(2)*1 + 'm';
        }
        _this.setData({dr:{time:time,juli:juli}});
      },
      fail: function (error) {
        console.error(error);
      }
    });
  },
  onShareAppMessage: function (res) {
    return {
      title: '我在'+this.data.house.name+'('+this.data.room.name+')要一起吗？',
      path: '/pages/content/index?id='+this.data.id+'&pid='+this.data.pid
    }
  },
  onShareTimeline: function () {
    return {
      title: '我在共享茶室等你',
      query: '/pages/map/index',
      imageUrl:'/image/share.jpg'
    }
  }
})